function textCounter(field, cntfield, maxlimit) {
    if (field.value.length > maxlimit) // if too long...trim it!
        field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
    else
        cntfield.value = maxlimit - field.value.length;
}
function confirm_login(message) {
    var temp = confirm(message);
    if (temp == true) {
        window.location = BASE_URL + "/index.php/users/login";
    } else {
        return false;
    }
}
$(document).ready(function () {
    $('.btn-bid2').click(function () {
        $('html,body').animate({scrollTop: $('.btn-bid').offset().top - 100}, 'slow');
    });
    $('.bid-tooltip').tooltip({
        trigger: 'manual'
    }).tooltip('show');
    $(".footer-info > div:last-child").click(function () {
        $('html, body').animate({scrollTop: 0}, 'slow');
        return false;
    });
    $('#horiz_container_outer').horizontalScroll();
    $('#btn-edit-profile').click(function () {
        $("#frm-edit-profile input,textarea").show();
        $("#frm-edit-profile #btn-save-profile").show();
        $("#frm-edit-profile #btn-cancel-save-profile").show();
    });
    $('#btn-cancel-save-profile').click(function () {
        $("#frm-edit-profile input,textarea").hide();
        $("#frm-edit-profile #btn-save-profile").hide();
        $("#frm-edit-profile #btn-cancel-save-profile").hide();
    });
    $('#add-resume').click(function () {
        $('.btn-resume li:last-child').before("<li><span><form id='frm-edit-resume' method='POST'><input class='form-control' name='resume' required style='margin-bottom: 10px;' type='text' /> <button type='button' onclick='editResume()' id='btn-save-resume' name='submit' value='submit' style='margin-right: 5px;' class='btn btn-primary'>Save</button><button type='button' id='btn-cancel-resume' class='btn btn-default'>Cancel</button></form></span></li>")
    });

    $('.btn-resume').on('click', '#btn-cancel-resume', function () {
        $(this).parent().parent().parent().remove();
    });

    $('#add-skill').click(function () {
        $('.btn-skill li:last-child').before("<li><span><form id='frm-edit-skill' method='POST'><input class='form-control' name='skill' required style='margin-bottom: 10px;' type='text' /> <button type='button' onclick='editSkill()' id='btn-save-skill ' name='submit' value='submit' style='margin-right: 5px;' class='btn btn-primary'>Save</button><button type='button' id='btn-cancel-skill' class='btn btn-default'>Cancel</button></form></span></li>")
    });
    $('.btn-skill').on('click', '#btn-cancel-skill', function () {
        $(this).parent().parent().parent().remove();
    });
    if ($('#budget option:selected').val() == 'customize') {
        $('#customize_budget').show();
    } else {
        $('#customize_budget').hide();
    }
    $('#budget').change(function () {
        if ($('#budget option:selected').val() == 'customize') {
            $('#customize_budget').show();
        } else {
            $('#customize_budget').hide();
        }
    });
    $("#bidAmt").on('input', function () {
        $("#bid-receive").html($("#bidAmt").val() - 5);
        $("#bid_paid").val($("#bidAmt").val() - 5);
    });

    // view detail Portfolio
    $('.detail-portfolio').on('click', function () {
        var pid = $(this).attr('data-id');
        $.ajax({
            type: "POST",
            url: BASE_URL + "index.php/programmer/ajaxPortfolio",
            data: ({portid: pid}),
            success: function (respond) {
                $('#ajax-modal').html(respond);
                $('#ajax-modal').modal();
            }
        });
    });

    // load view add review buyer
    $('.review-buyer').on('click', function () {
        var url = $(this).attr('data-href');
        $.get(url, function (data) {
            $('#ajax-modal2').html(data);
            $('#ajax-modal2').modal();
        });
    });

    // load view invite program
    $('.btn-invite').on('click', function () {
        var url = $(this).attr('data-href');
        $.get(url, function (data) {
            $('#ajax-modal2').html(data);
            $('#ajax-modal2').modal();
        });
    });
    $('.btn_invite_dev').on('click', function () {
        var url = $(this).attr('data-href');
        $.get(url, function (data) {
            $('#ajax-modal2').html(data);
            $('#ajax-modal2').modal();
        });
    });
    // pop-up login
    $("#link-log-in").click(function (e) {
        e.preventDefault();
        $("#login-modal").modal('show');
    })// end tag <a> click

    /**
     * Select with Search
     */
    jQuery(".chzn-select").chosen({
        no_results_text: "Không tìm thấy: ",
        enable_split_word_search: false,
        width: "100%"
    });

    $('.chosen-select').chosen();

    // select group
    $('.sl-group').change(function () {
        var id = $(this).val();

        $.ajax({
            type: "POST",
            url: BASE_URL + "index.php/project/ajaxGetCategories",
            data: ({group_id: id}),
            success: function (data) {
                var res = $.parseJSON(data);
                var html = "<select class='form-control multiple col-lg-12 sl-skill chzn-select'>" +
                    "<option>-- Please select --</option>";
                $.each(res, function () {
                    html += "<option value=" + this['id'] + ">" + this['category_name'] + "</option>";
                });
                html += "</select>";
                $('.div-skill').html(html);
                $('.chzn-select').chosen({
                    no_results_text: "Không tìm thấy: ",
                    enable_split_word_search: false,
                    width: "100%"
                });

            }
        });
    });

    // change select skill
    $('.sl-skill').on('change', function () {
        var category_id = $(this).val();
        var href_current = window.location.href;
        var uri = window.location.pathname;
        var arrUri = uri.split('/');
        var tmpUri = arrUri;
        var url = "/";// BASE_URL;

        if (arrUri[6] != undefined && arrUri[6] != '') {
            category_ids = arrUri[6].split(",");

            // remove 2 last element
            tmpUri.splice(5, 2);
            var uriNew = tmpUri.join('/');
            while (uriNew.charAt(0) === '/') {
                uriNew = uriNew.slice(1);
            }

            if (category_ids.indexOf(category_id) >= 0) {
                url += uriNew + "/0/" + category_ids;
            } else {
                url += uriNew + "/0/" + category_ids + "," + category_id;
            }

            window.location.href = url;
        } else {
            tmpUri.splice(5, 2);
            var uriNew = tmpUri.join('/');
            while (uriNew.charAt(0) === '/') {
                uriNew = uriNew.slice(1);
            }

            url += uriNew + "/0/" + category_id;

            window.location.href = url;
        }
    });

    if ($('#cate-milestone option:selected').text() == 'Customize') {
        $("#btn-create-milestone").show();
    } else {
        $("#btn-create-milestone").hide();
        $("#save-milestone").hide();
    }
    $('#cate-milestone').change(function () {
        if ($('#cate-milestone option:selected').text() == 'Customize') {
            $("#btn-create-milestone").show();
        } else {
            $("#btn-create-milestone").hide();
            $("#save-milestone").hide();
        }
    });

    // get skill by group


    // get skill by device
    $('.label-device input:checkbox').change(function () {
        var categoryIds = $(this).attr('data-categories');
        var $this = $(this);
        /*if($this.is(':checked')){
         alert('check');
         }else{
         alert('uncheck');
         }*/
        $.ajax({
            type: "POST",
            url: BASE_URL + "index.php/project/ajaxGetCategories",
            data: ({ids: categoryIds}),
            beforeSend: function () {
                //setTimeout(function(){
                $('.sticky-skill').append('<span class="loading-1"></span>');
                //}, 3000);
            },
            success: function (data) {
                $('.sticky-skill').find('.loading-1').remove();

                var res = $.parseJSON(data);
                var html = '';

                var skillCur = [];
                var skillNameCur = [];
                $.each($('#skills option'), function (index, val) {
                    skillCur.push(this.value);
                });
                $.each($('.sticky-skill label'), function (index, val) {
                    skillNameCur.push(this.textContent);
                });

                var catHidden = '';
                if ($this.is(':checked')) {
                    $.each(res, function (index, val) {
                        if ($.inArray(val['id'], skillCur) == -1 && $.inArray(val['category_name'], skillNameCur) == -1 ) {
                            html += "<label class='label-skill' data-value=" + val['id'] + ">" + val['category_name'] + "</label>";
                        }else {
                            $(this).attr('checked', true);
                        }
                    });
                    //$this.attr('data-categories-hidden', catHidden);
                } else {
                    $.each($('.sticky-skill label'), function (i, v) {
                        var idOld = this.getAttribute("data-value");
                        var $this = $(this);

                        $.each(res, function (index, val) {
                            if (val['id'] == idOld) {
                                $this.fadeOut(300, function () {
                                    $this.remove();
                                });
                                //$this.remove();
                            }
                        });
                    });
                }

                $(html).hide().appendTo(".sticky-skill").fadeIn(300);


            }
        });
    });

    $('body').on('click', '.label-skill', function () {
        var id = $(this).attr('data-value');
        var title = $(this).text().trim();

        if ($(this).hasClass('active-skill')) {
            $(this).removeClass('active-skill');
            $.each($('#skills option'), function (index, val) {
                var $this = $(this);
                if (this.value == id) {
                    $this.remove();
                }
            });

            $('#skills').trigger('liszt:updated');
        } else {
            $(this).addClass('active-skill');
            var html = "<option value='" + id + "' selected>" + title + "<option>";

            $('#skills').append(html);
            $('#skills').trigger('liszt:updated');
        }
    });

    // chose project template
    $('.label-template input:radio').change(function () {
        var id = $(this).val();

        window.location.href = BASE_URL + "index.php/project/create/t/" + id;
    });

    // get skill by device
    $('.label-device input:radio').change(function () {
        var categoryIds = $(this).attr('data-categories');
        $.ajax({
            type: "POST",
            url: BASE_URL + "index.php/project/ajaxGetCategories",
            data: ({ids: categoryIds}),
            success: function (data) {
                var res = $.parseJSON(data);
                var html = '';

                $.each($('select[name="project_categories[]_helper1"] option'), function (index, val) {

                    html += "<option value=" + this.value + ">" + this.innerText + "</option>";
                });

                $.each(res, function (index, val) {
                    html += "<option value=" + val['id'] + " selected>" + val['category_name'] + "</option>";

                });
                listBoxSkill.html(html);
                listBoxSkill.trigger('bootstrapDualListbox.refresh');
            }
        });
    });
    $('#more-country').click(function () {
        var $this = $(this);
        $.get(BASE_URL + "index.php/project/ajaxGetCountries", function (data) {
            var res = $.parseJSON(data);
            var html = '';
            $.each(res, function (k, v) {
                html += "<label class='label-country'><input type='checkbox' name='locations[]' value=" + v.id + "> " + v.country_name + "</label>";
            });
            $('.countries').append(html);
            $this.remove();
        });
    });

    // sort dev
    $('.select-sort').change(function () {
        var dir = $(this).find("option:selected").data("dir");
        $('#dir').val(dir);
        $(this).parent().submit();
    });

    // select option boottrap
    $('.selectpicker').selectpicker();

    // select category child
    $('#ChildCategory').on('change', 'input:checkbox', function(){
        var groupId = $(this).val();
        var $this = $(this);

        $.ajax({
            type: "POST",
            url: BASE_URL + "index.php/project/ajaxGetCategories",
            data: ({group_id: groupId}),
            success: function (data) {
                var res = $.parseJSON(data);
                var html = '';

                if($this.is(":checked") === true) {
                    $.each(res, function (index, val) {
                        html += "<option value='" + val['id'] + "'>" + val['category_name'] + "</option>";
                    });
                    $('#skills').append(html);
                    $("#skills").trigger('liszt:updated');
                }else if($this.is(":checked") === false){
                    $.each(res, function (index, val) {
                        $.each($('#skills option'), function (i) {
                            var $this = $(this);
                            if(this.value == val['id']) {
                                $this.remove();
                            }
                        });
                    });
                    $('#skills').append(html);
                    $("#skills").trigger('liszt:updated');
                }

            }
        });
    });

    // multiselect bootstrap
    /*$('#ChildCategory').multiselect({
        numberDisplayed: 1,
        nonSelectedText: '-- Vui lòng chọn --',
        buttonWidth: '100%',
        buttonClass: 'form-control',
        onChange: function(element, checked) {
            var groupId = $(element).val();

            $.ajax({
                type: "POST",
                url: BASE_URL + "index.php/project/ajaxGetCategories",
                data: ({group_id: groupId}),
                success: function (data) {
                    var res = $.parseJSON(data);
                    var html = '';

                    if(checked === true) {
                        $.each(res, function (index, val) {
                            html += "<option value='" + val['id'] + "'>" + val['category_name'] + "</option>";
                        });
                        $('#skills').append(html);
                        $("#skills").trigger('liszt:updated');
                    }else if(checked === false){
                        $.each(res, function (index, val) {
                            $.each($('#skills option'), function (i) {
                                var $this = $(this);
                                if(this.value == val['id']) {
                                    $this.remove();
                                }
                            });
                        });
                        $('#skills').append(html);
                        $("#skills").trigger('liszt:updated');
                    }

                }
            });
        }
    });*/

    // validate error
    $('.error').parents('.form-group').addClass('has-error');

    $('#btn-status-project').confirmation({
        popout:true
    });

    // add wishlist project
    $('body').on('click','.project-wishlist', function(){
        var id = $(this).attr('data-id');
        var redirect_url = $(this).attr('data-url');
        var $this = $(this);

        $.ajax({
            type: "POST",
            url: BASE_URL + "index.php/joblist/ajaxAddProjectWishlist",
            data: ({project_id: id}),
            success: function (data) {
                var res = $.parseJSON(data);

                if(res.status === "FAIL") {
                    var html = '<input type="hidden" name="project_id" value="' + id + '">' +
                                '<input type="hidden" name="redirect_url" value="' + redirect_url + '">';
                    $("#login-popup-form").append(html);
                    $("#login-modal").modal('show');
                }else if(res.status === "SUCCESS"){
                    //BootstrapDialog.alert('Job đã được thêm vào danh sách yêu thích');
                    $this.removeClass('project-wishlist glyphicon-heart-empty');
                    $this.addClass('active-wishlist glyphicon-heart');
                }

            }
        });
    });

    // remove wishlist
    $('body').on('click', '.active-wishlist', function(){
        var id = $(this).attr('data-id');
        var redirect_url = $(this).attr('data-url');
        var $this = $(this);

        $.ajax({
            type: "POST",
            url: BASE_URL + "index.php/joblist/ajaxRemoveProjectWishlist",
            data: ({project_id: id}),
            success: function (data) {
                var res = $.parseJSON(data);

                if(res.status === "FAIL") {
                    var html = '<input type="hidden" name="project_id" value="' + id + '">' +
                        '<input type="hidden" name="redirect_url" value="' + redirect_url + '">';
                    $("#login-popup-form").append(html);
                    $("#login-modal").modal('show');
                }else if(res.status === "SUCCESS"){
                    //BootstrapDialog.alert('Job đã được xóa ra khỏi danh sách yêu thích');
                    $this.removeClass('active-wishlist glyphicon-heart');
                    $this.addClass('project-wishlist glyphicon-heart-empty');
                }

            }
        });
    });

    // chose type budget
    $("#frm-bubget input:radio").change(function(){
        var type = $(this).val();

        $("#frm-bubget label").removeClass('active');
        $(this).parent().addClass('active');

        if(type == 2){
            $("#frm-bubget .budget").attr('disabled', false);
        }else{
            $("#frm-bubget .budget").attr('disabled', true);
        }
    });

    // job description read more
    $("body").on('click', '.des-readmore', function(){
        var id = $(this).attr('data-id');
        var $this = $(this);

        $.ajax({
            type: "POST",
            url: BASE_URL + "index.php/project/ajaxGetProject",
            data: ({project_id: id}),
            beforeSend: function () {
                $this.after('<span class="loading-1"></span>');
            },
            success: function (data) {
                $('.loading-1').remove();
                var res = $.parseJSON(data);
                $this.parent('.project-des').html(res.description);
            }
        });
    });

    // submit project status
    $('.select-project-status').change(function(){
        var id = $(this).val();
        var href_current = BASE_URL + 'index.php/buyer/viewMyProjects';
        if(id != ''){
            href_current += '/st/'+id;
        }

        window.history.pushState({}, '', href_current);
        $(this).parent('form').submit();
    });

    // submit project status
    $('.select-project-status-dev').change(function(){
        var id = $(this).val();
        var href_current = BASE_URL + 'index.php/programmer/viewMyProjects';
        if(id != ''){
            href_current += '/st/'+id;
        }

        window.history.pushState({}, '', href_current);
        $(this).parent('form').submit();
    });

    $("#flexiselDemo").flexisel({
        visibleItems: 4,
        animationSpeed: 800,
        autoPlay: false,
        autoPlaySpeed: 5000,
        pauseOnHover: true,
        enableResponsiveBreakpoints: true,
        responsiveBreakpoints: {
            mobi: {
                changePoint:340,
                visibleItems: 1
            },
            portrait: {
                changePoint:480,
                visibleItems: 1
            },
            landscape: {
                changePoint:640,
                visibleItems: 2
            },
            tablet: {
                changePoint:768,
                visibleItems: 2
            },
            pc: {
                changePoint:1024,
                visibleItems: 4
            }
        }
    });

    // remove watchlist
    $('.btn-remove-watchlist').click(function(){
        var id = $(this).attr('data-id');
        var $this = $(this);

        BootstrapDialog.confirm('Are you want remove item?', function(result){
            if(result === true) {
                $.ajax({
                    type: "POST",
                    data : "user_id="+id,
                    url : BASE_URL+"index.php/users/removeWatchList",
                    success:function(data){
                        var data = $.parseJSON(data);
                        if(data.status == 'success'){
                            $this.parents('.item-'+id).fadeOut().remove();
                        }

                    }
                });
            }
        });
    });
    //ajaxgetChildCategory();

    // click tabs message
    $('.menu-message li').unbind('click').click(function (){
        var href_current = BASE_URL + 'index.php/buyer/messages';
        var link = $(this).find('a').attr('href');
        if(link != ''){
            href_current += '/'+link;
        }

        window.history.pushState({}, '', href_current);
});

    $('.ajax-pagination').on('click','a', function(e){
        e.preventDefault();

        var url = $(this).parents('.ajax-pagination').attr('data-url');
        var target = $(this).parents('.ajax-pagination').attr('data-target');
        var target_pagination = $(this).parents('.ajax-pagination');
        var link = $(this).attr('href');
        var page = $(this).attr('data-page');

        if(link != '' || link != '#'){
            window.history.pushState({}, '', link);

            $.ajax({
                type: "POST",
                url : url,
                data : "p=" + page,
                beforeSend: function(){
                    $('body').append('<div class="loader"><div class="overlay-loading"></div><div class="loading-2"></div></div>');
                },
                success:function(data){
                    var data = $.parseJSON(data);

                    if(data.message_send != ''){
                        var html = '';

                        $.each(data.items, function (index, val) {
                            var logo = BASE_URL + '/app/css/images/default-images.jpg';

                            if(fileExists(BASE_URL + '/files/logos/'+val['logo']) && val['logo'] != ''){
                                logo = BASE_URL + '/files/logos/'+val['logo'];
                            }

                            html += '<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 no-padding item-mess">' +
                            '<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">' +
                            '<div class="table-cell"><input type="checkbox" data-id="'+val['id']+'"></div></div>' +
                            '<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1 no-padding">' +
                            '<a href="#">' +
                            '<img src="'+logo+'" class="img-responsive">' +
                            '</a>' +
                            '</div>' +
                            '<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">' +
                            '<div class="table-cell">' +
                            '<a href="#">'+val['user_name']+'</a>' +
                            '<p>13 hrs ago</p>' +
                            '</div>' +
                            '</div>' +
                            '<div class="col-lg-7 col-md-7 col-sm-7 col-xs-7">' +
                            '<div class="table-cell">' +
                            '<span class="subject-message">'+val['subject']+'</span>' +
                            '<p>'+val['message']+'</p>' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                        });
                        $(target).html(html);
                        target_pagination.html(data.pagination);

                        setTimeout(function() {
                            $('body').find('.loader').remove();
                        }, 200);
                    }
                }
            });
        }

        return false;
    });

    // chose all item message
    $('.checkall').click(function(){
        var item = $('#message_inbox').find('.checkbox');

        if($(this).is(':checked')) {
            item.each(function(){
                this.checked = true;
            });
        } else {
            item.each(function(){
                $(this).attr('checked',false);
            });
        }
    });

    // mark label message
    $('.mark-mess').click(function(){
        var data = new Array();
        var status = $(this).attr('data-type');

        $('#message_inbox .checkbox').each(function(){
            if($(this).is(':checked')){
                data.push($(this).attr('data-id'));
            }
        });

        $.ajax({
            type: "POST",
            url: BASE_URL + 'index.php/buyer/ajaxMarkMessage',
            data: ({ids: data, status: status}),
            beforeSend: function(){
                $('body').append('<div class="loader"><div class="overlay-loading"></div><div class="loading-2"></div></div>');
            },
            success: function(data){
                var res = $.parseJSON(data);
                if(res.count_unread != undefined){
                    $("#count_unread").html(res.count_unread);
                }

                if(res.count_archive != undefined){
                    $("#count_archive").html(res.count_archive);
                }

                if(res.archive != undefined){
                    var html = '';
                    $.each(res.archive, function (index, val) {
                        var logo = BASE_URL + '/app/css/images/default-images.jpg';

                        if(fileExists(BASE_URL + '/files/logos/'+val['logo']) && val['logo'] != ''){
                            logo = BASE_URL + '/files/logos/'+val['logo'];
                        }

                        html += '<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 no-padding item-mess">' +
                        '<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">' +
                        '<div class="table-cell"><input type="checkbox" data-id="'+val['id']+'"></div></div>' +
                        '<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1 no-padding">' +
                        '<a href="#">' +
                        '<img src="'+logo+'" class="img-responsive">' +
                        '</a>' +
                        '</div>' +
                        '<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">' +
                        '<div class="table-cell">' +
                        '<a href="#">'+val['user_name']+'</a>' +
                        '<p>13 hrs ago</p>' +
                        '</div>' +
                        '</div>' +
                        '<div class="col-lg-7 col-md-7 col-sm-7 col-xs-7">' +
                        '<div class="table-cell">' +
                        '<span class="subject-message">'+val['subject']+'</span>' +
                        '<p>'+val['message']+'</p>' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '</div>';
                    });
                    $('#archive').html(html);
                }

                setTimeout(function() {
                    $('body').find('.loader').remove();
                }, 200);
            }
        });
    });

});
getMessages();
// BootstrapDialog
function modal(element, title, message, type) {
    if (type == 'alert') {
        BootstrapDialog.alert({
            title: title,
            message: message,
            closable: true,
            cssClass: 'btn-primary',
            callback: function (result) {
                return result;
                //result = result;
            }
        });
    } else if (type == 'confirm') {
        var href = $(element).attr('href');
        var dlg = new BootstrapDialog({
            title: title,
            message: message,
            closable: false,
            buttons: [{
                label: 'Yes',
                cssClass: 'btn-primary',
                id: 'btnYes',
                action: function (dialog) {
                    window.location.href = href;
                    dialog.close();
                }
            },
                {
                    label: 'No',
                    cssClass: 'btn',
                    id: 'btnNo',
                    action: function (dialog) {
                        dialog.close();
                    }
                }]
        });

        dlg.open();
    }
    return false;
}
function RemoveItemMilestone() {
    $("#item-milestone > div:last-child").remove();
}


function getMessages() {
    $.ajax({
        type: "POST",
        url: BASE_URL + "index.php/messages/getMessages",
        data: "track=0",
        beforeSend: function () {
            //$('#loading-notifications').show();
        },
        success: function (data) {
            $('#loading-notifications').hide();
            data = $.parseJSON(data);
            if ((data.status == 'error') || (data.status == 'no-data')) {
                $('#notifications-no-data').show();
            } else {
                if (data.result == 0) {
                    var n = noty({text: "<a style='color:#fff;' href='" + BASE_URL + "index.php/messages/showAllMessage'>" + "Có 1 tin nhắn mới" + "</a>"});
                }
            }
            setTimeout(function () {
                getMessages();
            }, 10000);
        }
    });
}
$.noty.defaults = {
    layout: 'bottomRight',
    theme: 'defaultTheme',
    type: 'information',
    text: "", // can be html or string
    dismissQueue: true, // If you want to use queue feature set this true
    template: '<div class="noty_message"><span class="noty_text"></span><div class="noty_close"></div></div>',
    animation: {
        open: {height: 'toggle'},
        close: {height: 'toggle'},
        easing: 'swing',
        speed: 500 // opening & closing animation speed
    },
    timeout: 500000, // delay for closing event. Set false for sticky notifications
    force: false, // adds notification to the beginning of queue when set to true
    modal: false,
    maxVisible: 5, // you can set max visible notification for dismissQueue true option,
    killer: false, // for close all notifications before show
    closeWith: ['click'], // ['click', 'button', 'hover']
    callback: {
        onShow: function () {
        },
        afterShow: function () {
        },
        onClose: function () {
        },
        afterClose: function () {
        }
    },
    buttons: false // an array of buttons
};

function loginGG() {
    urls = BASE_URL + "index.php/users/loginGoogle";
    jQuery.ajax({
        url: urls,
        type: 'POST',
        success: function (obj) {
            var res = jQuery.parseJSON(obj);

            if (res.status == "ERROR") {
                //window.open(res.url,'_blank');
                window.location.href = res.url;
                //popup_window = openPopupWindow(res.url);
            } else if (res.status == "OK") {
                popup_window.close();
            }
        }
    });

}
$('.btn-login-facebook').click(function () {
    var pr_id = $(this).attr('data-id');

    //return false;
    FB.getLoginStatus(function (sttRes) {

        if (sttRes.status === 'connected') {
            console.log('Logged in.');
            var email;
            var name;
            FB.login(function () {
                FB.api('/me/feed', 'post', {message: "Hello world"});
                FB.api('/me', function (response) {
                    email = response.email;
                    name = response.name;
                    var id = response.id;
                    //$('#email-facebook').text(response.email);
                    //$('#name-facebook').text(name);
                    console.log(email);
                    if (response.email == null) {
                        alert('Email chưa verify');
                    }
                    //console.log(response);
                    $.ajax({
                        type: "POST",
                        data: "email=" + email + "&response=" + JSON.stringify(response),
                        url: BASE_URL + "/index.php/buyer/registerFacebook",
                        success: function (data) {
                            var data = $.parseJSON(data);
                            if (data.status == "not-exist") {
                                $("#email").val(email);
                                $("#modal-facebook-register").modal('show');
                                $(".image-avatar-facebook").attr('src', "https://graph.facebook.com/" + response.id + "/picture?type=large");
                            }
                            if (data.status == "email-exist") {
                                $("#modal-login-facebook").modal('show');
                                $(".image-avatar-facebook").attr('src', "https://graph.facebook.com/" + response.id + "/picture?type=large");
                                $("#email-login-facebook").text(email);
                            }
                            if (data.status == "email-facebook-exist") {
                                $.ajax({
                                    type: "POST",
                                    data: "email=" + email,
                                    url: BASE_URL + "index.php/buyer/loginFacebook",
                                    success: function (data) {
                                        var data = $.parseJSON(data);
                                        if (data.status == 'success') {
                                            if (data.role == 1) {
                                                if(typeof pr_id !== "undefined") {
                                                    window.location.href = BASE_URL + 'index.php/project/create/'+pr_id;
                                                }else {
                                                    window.location.href = BASE_URL + 'index.php/buyer/viewMyProjects';
                                                }
                                            }
                                            else
                                                window.location.href = BASE_URL + 'index.php/programmer/viewMyProjects';
                                        }
                                    }
                                });

                            }
                        }
                    });
                });
            }, {scope: 'email'});
        }
        else {
            FB.login(function () {
                FB.api('/me', function (response) {
                    $.ajax({
                        type: "POST",
                        data: "email=" + response.email + "&response=" + JSON.stringify(response),
                        url: BASE_URL + "/index.php/buyer/registerFacebook",
                        success: function (data) {
                            var data = $.parseJSON(data);
                            if (data.status == "not-exist") {
                                console.log(response);
                                $("#email").val(response.email);
                                $("#modal-facebook-register").modal('show');
                                $(".image-avatar-facebook").attr('src', "https://graph.facebook.com/" + response.id + "/picture?type=large");
                            }
                            if (data.status == "email-exist") {
                                $("#modal-login-facebook").modal('show');
                                $(".image-avatar-facebook").attr('src', "https://graph.facebook.com/" + response.id + "/picture?type=large");
                                $("#email-login-facebook").text(response.email);
                            }
                            if (data.status == "email-facebook-exist") {
                                $.ajax({
                                    type: "POST",
                                    data: "email=" + response.email,
                                    url: BASE_URL + "index.php/buyer/loginFacebook",
                                    success: function (data) {
                                            var data = $.parseJSON(data);
                                            if (data.status == 'success') {
                                                if (data.role == 1) {
                                                    if(typeof pr_id !== "undefined") {
                                                        window.location.href = BASE_URL + 'index.php/project/create/'+pr_id;
                                                    }else {
                                                        window.location.href = BASE_URL + 'index.php/buyer/viewMyProjects';
                                                    }
                                                }
                                                else
                                                    window.location.href = BASE_URL + 'index.php/programmer/viewMyProjects';
                                            }
                                    }
                                });
                            }
                        }
                        //$("#email-facebook").val(response.email);
                    });
                });
            },{scope:'email'});
        }
    });
});
    function ajaxgetChildCategory() {
        var arrData = [];
        $.ajax({
            type: "POST",
            url: BASE_URL + "index.php/project/getChildCategory",
            data: "id_category=" + $('#ParentCategory').val(),
            beforeSend: function () {
                $('#ParentCategory').parent().append('<span class="loading-1"></span>');
            },
            success: function (data) {
                $('#ParentCategory').parent().find(".loading-1").remove();

                var res = $.parseJSON(data);
                if (res.status == "success") {
                    var html = '';
                    $('#ChildCategory').empty();
                    $('#ChildCategoryProfile').empty();
                    $.each(res.data, function (k) {
                        html += "<label class='label-category'>" +
                                "<input type='checkbox' name='group[]' value='" + res.data[k].id + "' />" + res.data[k].group_name + "</label>";
                    });
                    $('#ChildCategoryProfile').html(html);
                    $('#ChildCategory').html(html);
                }
            }
        });
    }


    function initiateSignIn() {
        var params = {
            'clientid': '754619413177-28dp7gjl950vqsaq1tmlri9k9epoobs9.apps.googleusercontent.com',
            'cookiepolicy': BASE_URL,
            'callback': 'onSignInCallback',
            'scope': 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email',
            'requestvisibleactions': 'http://schemas.google.com/AddActivity'
        };
        gapi.auth.signIn(params);
    }

    function onSignInCallback(resp) {
        gapi.client.load('plus', 'v1', apiClientLoaded);
        gapi.client.load('oauth2', 'v2', apiClientLoaded2);
    }

    function apiClientLoaded() {
        gapi.client.plus.people.get({userId: 'me'}).execute(handleEmailResponse);
    }

    function apiClientLoaded2() {
        gapi.client.oauth2.userinfo.get().execute(handleEmailResponse);
    }

    function handleEmailResponse(resp) {
        var email;
        var avatar;

        var arAvatar = resp.image.url.split('?sz=');
        avatar = arAvatar[0] + '?sz=200';

        for (var i = 0; i < resp.emails.length; i++) {
            if (resp.emails[i].type === 'account') {
                email = resp.emails[i].value;
            }
        }

		var pid = $('#btn-google').attr('data-id');
        $.ajax({
            type: "POST",
            data: "email=" + email + "&response=" + JSON.stringify(resp),
            url: BASE_URL + "/index.php/buyer/registerGoogle",
            success: function (data) {

                var data = $.parseJSON(data);
                if (data.status == "not-exist") {
                    $("#modal-google-register input[name='email']").val(email);
                    $("#modal-google-register").modal('show');
                    $(".image-avatar-google").attr('src', avatar);
                } else if (data.status == "google-exist") {
                    $("#modal-login-google").modal('show');
                    $(".image-avatar-google").attr('src', avatar);
                    $("#email-login-google").text(email);
                } else if (data.status == "email-exist") {
                    $.ajax({
                        type: "POST",
                        data: "email=" + email,
                        url: BASE_URL + "index.php/buyer/loginFacebook",
                        success: function (data) {
                            var data = $.parseJSON(data);
                            if(data.status == 'success'){
                            if(pid > 0){
                                if(data.role == 1)
                                    window.location.href = BASE_URL+'index.php/project/create/'+pid;
                                else
                                    window.location.href = BASE_URL+'index.php/buyer/editProfileUpdate';
                            } else{
                                if(data.role == 1)
                                    window.location.href = BASE_URL+'index.php/buyer/viewMyProjects';
                                else
                                    window.location.href = BASE_URL+'index.php/programmer/viewMyProjects';
                            }
                        }
                        }
                    });
                    //$("#modal-login-google").modal('show');
                    //$("#email-login-google").text(email);
                    //$(".image-avatar-google").attr('src', avatar);
                }
            }
        });
    }

    $('.item-dev-recommend').popover({
        html: true,
        trigger: 'manual',
        placement: 'bottom',
        content: function () {
            return $('#popover_info_dev_1').html();
        }
    }).on("mouseenter", function () {
        var _this = this;
        $(this).popover("show");
        $(this).siblings(".popover").on("mouseleave", function () {
            $(_this).popover('hide');
        });
    }).on("mouseleave", function () {
        var _this = this;
        setTimeout(function () {
            if (!$(".popover:hover").length) {
                $(_this).popover("hide")
            }
        }, 100);
    });
$('#btn-status-project').confirmation({
    popout:true
});
$('body').on('click','#btn-invite-one', function () {
    var url = $(this).attr('data-href');
    $.get(url, function (data) {
        $('#ajax-modal2').html(data);
        $('#ajax-modal2').modal();
    });
    //if($("#ajax-modal").attr('data-success') == "success"){
    //    alert('aaaaa');
    //}
});
$('body').on('click','#btn-watchlist',function(){
    var user_id = $(this).parent().attr('data-id');
    var target_click = $(this);
    if($(this).hasClass(('glyphicon-heart'))){
        $.ajax({
            type: "POST",
            data : "user_id="+user_id,
            url : BASE_URL+"index.php/users/removeWatchList",
            success:function(data){
                var data = $.parseJSON(data);
                if(data.status == 'success'){
                    target_click.removeClass('glyphicon-heart');
                    target_click.addClass('glyphicon-heart-empty');
                }
                if(data.status == 'not-client'){
                    alert('not client');
                }
                if(data.status == 'not-login'){
                    if(document.getElementById('dev_save') == null) {
                        var html = '<input type="hidden" name="dev_id" id="dev_save" value="' + user_id + '">';
                    }
                    else {
                        $('#dev_save').remove();
                        var html = '<input type="hidden" name="dev_id" id="dev_save" value="' + user_id + '">';
                    }
                    $("#login-popup-form").append(html);
                    $("#login-modal").modal('show');
                }
            }
        });
    }
    if($(this).hasClass(('glyphicon-heart-empty'))){
        $.ajax({
            type: "POST",
            data : "user_id="+user_id,
            url : BASE_URL+"index.php/users/addWatchList",
            success:function(data){
                var data = $.parseJSON(data);
                if(data.status == 'success'){
                    target_click.removeClass('glyphicon-heart-empty');
                    target_click.addClass('glyphicon-heart');
                }
                if(data.status == 'not-client'){
                    alert('not client');
                }
                if(data.status == 'not-login'){
                    if(document.getElementById('dev_save') == null) {
                        var html = '<input type="hidden" name="dev_id" id="dev_save" value="' + user_id + '">';
                    }
                    else {
                        $('#dev_save').remove();
                        var html = '<input type="hidden" name="dev_id" id="dev_save" value="' + user_id + '">';
                    }
                    $("#login-popup-form").append(html);
                    $("#login-modal").modal('show');
                    $("#login-modal").modal('show');
                }
            }
        });
    }
});
$('.find-freelancer-country').on('change', function () {
    var url = $(this).val(); // get selected value
    if (url) { // require a URL
        window.location = url; // redirect
    }
    return false;
});
$('.more-desc').on('click',function(){
    if($(this).text() == 'more'){
        $(".full-desc").show();
        $(".short-desc").hide();
        $(this).text('hide');
    }else{
        $(".short-desc").show();
        $(".full-desc").hide();
        $(this).text("more");
    }
});

function getInfoUser(userId){
    var result = '';
    $.ajax({
        type: "POST",
        data : "user_id="+userId,
        url : BASE_URL+"index.php/users/ajaxGetInfoUser",
        success:function(data){
            var res = $.parseJSON(data);
            result = res;
        }
    });

    return result;
}

function fileExists(url) {
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}
$('.child-category-profile').on('change', 'input:checkbox', function(){
    var groupId = $(this).val();
    var $this = $(this);

    $.ajax({
        type: "POST",
        url: BASE_URL + "index.php/project/ajaxGetCategories",
        data: ({group_id: groupId}),
        success: function (data) {
            var res = $.parseJSON(data);
            var html = '';
            var li_html = "<ul>";

            if($this.is(":checked") === true) {
                $.each(res, function (index, val) {
                    html += "<option value='" + val['id'] + "'>" + val['category_name'] + "</option>";
                    li_html += "<li data-value='" + val['id'] +"' class='label-skill'>"+val['category_name']+"</li>";
                });
                li_html += "</ul>";
                $('#skills').append(html);
                $('#stick-skills').append(li_html);
                $("#skills").trigger('liszt:updated');
            }else if($this.is(":checked") === false){
                $.each(res, function (index, val) {
                    $.each($('#stick-skills li'), function (i) {

                        var $this = $(this);
                        if($this.attr('data-value') == val['id']) {
                            $this.remove();
                        }
                    });
                    $.each($('#skills option'), function (i) {

                        var $this2 = $(this);
                        if($this2.attr('value') == val['id']) {
                            $this2.remove();
                        }
                    });
                });
                $('#skills').append(html);
                $('#stick-skills').append(li_html);
                $("#skills").trigger('liszt:updated');
            }

        }
    });
});
function ajaxgetChildCategoryProfile(list_group_ids) {

    if(list_group_ids != 0){
        list_group_ids = list_group_ids.split(',');
    }


    var arrData = [];
    $.ajax({
        type: "POST",
        url: BASE_URL + "index.php/project/getChildCategory",
        data: "id_category=" + $('#ParentCategory').val(),
        beforeSend: function () {
            $('#ParentCategory').parent().append('<span class="loading-1"></span>');
        },
        success: function (data) {
            $('#ParentCategory').parent().find(".loading-1").remove();

            var res = $.parseJSON(data);
            if (res.status == "success") {
                var html = '';
                $('#ChildCategory').empty();
                $('#ChildCategoryProfile').empty();
                $.each(res.data, function (k) {

                    if($.isArray(list_group_ids))
                    {
                        //console.log($.inArray(res.data[k].id,list_group_ids));
                        if(($.inArray(res.data[k].id,list_group_ids)) >= '0') {

                            checked = 'checked="checked"';
                        }
                        else {
                            checked = '';
                        }
                    }


                    html += "<label class='label-category'>" +
                    "<input type='checkbox' "+checked+"  name='group[]' value='" + res.data[k].id + "' />" + res.data[k].group_name + "</label>";
                });
                $('#ChildCategoryProfile').html(html);
                $('#ChildCategory').html(html);
            }
        }
    });
}

function getNumBid(projectId){
    var num_bid = 0;
    $.ajax({
        type: "POST",
        async: false,
        url: BASE_URL + "index.php/project/ajaxGetNumBid",
        data: "projectId=" + projectId,
        success: function (data) {
            num_bid = data;
        }
    });

    return num_bid;
}

function getCategoryLink(category_ids){
    var strCategory = '';
    $.ajax({
        type: "POST",
        async: false,
        url: BASE_URL + "index.php/project/ajaxGetCategoryLink",
        data: "category_ids=" + category_ids,
        success: function (data) {
            strCategory = data;
        }
    });

    return strCategory;
}

function cutString(string, lenght, char){
    if(string == ''){
        return '';
    }
    if(lenght > string.length){
        return string;
    }

    string = string.substr(0,lenght);
    string = string.split('').reverse().join('');
    var pos = string.indexOf(' ');
    string = string.substr((pos + 1));
    string = string.split('').reverse().join('');

    return string + ' ' + char;
}